package com.zxkj.commonpatrol.adapt;

import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Build;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentManager;

import com.SuperKotlin.pictureviewer.ImagePagerActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.czy.basecommon.utils.base.BaseRepository;
import com.czy.basecommon.utils.constant.ItrackConstant;
import com.czy.basecommon.utils.tools.ActivityTool;
import com.czy.basecommon.utils.tools.MyImageLoader;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.PictureSelector;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.bottomsheet.BottomSheet;
import com.xuexiang.xui.widget.toast.XToast;
import com.zxkj.commonpatrol.R;
import com.zxkj.commonpatrol.model.entity.GroupMember;
import com.zxkj.commonpatrol.model.entity.itemPicEntity;
import com.zxkj.commonpatrol.model.entity.itemVioceEntity;
import com.zxkj.commonpatrol.model.response.MediaInfoResponse;
import com.zxkj.commonpatrol.ui.ShowMediaActivity;
import com.zxkj.commonpatrol.utils.MediaManager;
import com.zxkj.commonpatrol.view.VioceDialog;
import com.zxkj.commonpatrol.viewmodel.ShowMediaDetailViewModel;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class FzTestAdapt extends BaseQuickAdapter<MediaInfoResponse, BaseViewHolder> {
    private MiniLoadingDialog loadingDialog;

    private FragmentManager FragManager;
    private ShowMediaDetailViewModel viewModel;
    private List<BottomSheet.BottomListSheetBuilder.BottomSheetListItemData> mItemsVioce;
    private List<MediaInfoResponse> datas = new ArrayList<>();
    private List<MediaInfoResponse> Vicoedatas = new ArrayList<>();
    public FzTestAdapt(ShowMediaDetailViewModel viewModel, int layoutResId, @Nullable List<MediaInfoResponse> mediaInfoResponses, MiniLoadingDialog loadingDialog) {
        super(layoutResId, mediaInfoResponses);
        FragManager = ActivityTool.getInstance().getLastActivity().getSupportFragmentManager();
        this.loadingDialog = loadingDialog;
        if (mediaInfoResponses.size() > 0) {
            loadingDialog.show();
        }
        this.viewModel = viewModel;
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void convert(@NotNull BaseViewHolder helper, @Nullable MediaInfoResponse data) {

        ImageView iv_Pic = helper.itemView.findViewById(R.id.iv1);
        ImageView iv_Vioce = helper.itemView.findViewById(R.id.vioce);
        ImageView iv_Video = helper.itemView.findViewById(R.id.video);

        if (data.getPhoto() != null && data.getPhoto().size() > 0) {
            int adapterPosition = helper.getAdapterPosition();
            //add//判斷getPhotoPtahs null
            if (datas.size() > 0) {
               if (datas.size()>adapterPosition){
                   if (datas.get(adapterPosition).getPhotoPtahs() != null && datas.get(adapterPosition).getPhotoPtahs().size() > 0) {
                       MyImageLoader.load(getContext(), datas.get(adapterPosition).getPhotoPtahs().get(0), iv_Pic, R.drawable.nodatas);
                   }
               }

            }else {
                viewModel.mRepository.DownLoadPhoto("", ItrackConstant.Picture, "", 0, 0, data.getPhoto(), new BaseRepository.MyBaseDataCallBack() {
                    @Override
                    public void onDataSuccessCallBack(Object o) {
                        List<itemPicEntity> itemPicEntityList = (List<itemPicEntity>) o;
                        ArrayList<String> photoPaths = new ArrayList<>();
                        for (itemPicEntity itemPicEntity : itemPicEntityList) {
                            photoPaths.add(itemPicEntity.getPicPath());
                        }
                        MediaInfoResponse mediaInfoResponse = new MediaInfoResponse();
                        mediaInfoResponse.setPhotoPtahs(photoPaths);
                        datas.add(mediaInfoResponse);

                        if (helper.getLayoutPosition() + 1 == getData().size()) {
                            if (loadingDialog != null) {
                                loadingDialog.dismiss();
                            }
                            notifyDataSetChanged();


                        }
                    }

                    @Override
                    public void onDataFailCallBack(Object o, Object t1) {
                        if (helper.getLayoutPosition() + 1 == getData().size()) {
                            if (loadingDialog != null) {
                                loadingDialog.dismiss();
                            }


                        }
                    }
                });

            }

//            List<MediaInfoResponse.MediaPhoto> images = data.getPhoto();
//            List<String> collects = images.stream().map(p -> p.getPicPath()).collect(Collectors.toList());
//            collect = new ArrayList<>();
//            collect.addAll(collects);
//            MyImageLoader.load(getContext(),data.getPhoto().get(0).getPicPath(), iv_Pic, R.drawable.nodatas);

            } else {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
                iv_Pic.setImageDrawable(getContext().getDrawable(R.drawable.nodatas));

            }
            iv_Pic.setOnClickListener(v -> {
                int adapterPosition = helper.getAdapterPosition();
                if (datas.size() > 0&&datas.size()>adapterPosition) {

                    ArrayList<String> photoPtahs = datas.get(adapterPosition).getPhotoPtahs();
                    com.SuperKotlin.pictureviewer.PictureConfig config = new com.SuperKotlin.pictureviewer.PictureConfig.Builder()
                            .setListData(photoPtahs)    //图片数据List<String> list
                            .setPosition(0)    //图片下标（从第position张图片开始浏览）
                            .setIsShowNumber(true)//是否显示数字下标
                            .needDownload(false)    //是否支持图片下载
                            .setPlacrHolder(R.drawable.nodatas)    //占位符图片（图片加载完成前显示的资源图片，来源drawable或者mipmap）
                            .build();
                    ImagePagerActivity.startActivity(getContext(), config);
                } else {
                    XToast.error(getContext(), "暂无数据").show();
                }

            });

            // new BottomSheet.BottomListSheetBuilder(getContext())
            //
            //                            .addItem("查看大圖")
            //                            .addItem("刪除")
            //                            .setIsCenter(true)
            //                            .setOnSheetItemClickListener(new BottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
            //                                @RequiresApi(api = Build.VERSION_CODES.N)
            //                                @Override
            //                                public void onClick(BottomSheet dialog, View itemView, int position, String tag) {
            //                                    dialog.dismiss();
            //                                    List<itemPicEntity> images = getData().stream().filter(p -> p.getItemPicEntity() != null).map(p -> p.getItemPicEntity()).collect(Collectors.toList());
            //                                    List<String> collects = images.stream().map(p -> p.getPicPath()).collect(Collectors.toList());
            //                                    collect=new ArrayList<>();
            //                                    collect.addAll(collects);
            //
            //                                    if (position == 0) {
            //                                        com.SuperKotlin.pictureviewer.PictureConfig config = new com.SuperKotlin.pictureviewer.PictureConfig.Builder()
            //                                                .setListData(collect)    //图片数据List<String> list
            //                                                .setPosition(helper.getLayoutPosition())    //图片下标（从第position张图片开始浏览）
            //                                                .setIsShowNumber(true)//是否显示数字下标
            //                                                .needDownload(false)    //是否支持图片下载
            //                                                .setPlacrHolder(R.drawable.nodatas)    //占位符图片（图片加载完成前显示的资源图片，来源drawable或者mipmap）
            //                                                .build();
            //                                        ImagePagerActivity.startActivity(getContext(), config);
            //                                    } else {
            //
            //                                        remove(helper.getLayoutPosition());
            //                                    }
            //                                }
            //                            })
            //                            .build()
            //                            .show();


            iv_Vioce.setOnClickListener(v -> {

                if (data.getVoice() != null && data.getVoice().size() > 0) {
                       if (Vicoedatas.size()>0){
                           mItemsVioce=new ArrayList<>();
                           for (int i = 0; i < Vicoedatas.size(); i++) {
                               mItemsVioce.add(new BottomSheet.BottomListSheetBuilder.BottomSheetListItemData("录音" + i, ""));

                           }
                           BottomSheet.BottomListSheetBuilder bottomListSheetBuilder = new BottomSheet.BottomListSheetBuilder(getContext());
                           bottomListSheetBuilder.setmItems(mItemsVioce);
                           bottomListSheetBuilder.setIsCenter(true)
                                   .setOnSheetItemClickListener(new BottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                                       @Override
                                       public void onClick(BottomSheet dialog, View itemView, int position, String tag) {
                                           VioceDialog vioceDialog = VioceDialog.getInstance();
                                           vioceDialog.show(FragManager, "");

                                           MediaManager.playSound(Vicoedatas.get(0).getVoicePtahs().get(position), new MediaPlayer.OnCompletionListener() {
                                               @Override
                                               public void onCompletion(MediaPlayer mediaPlayer) {
                                                   vioceDialog.dismiss();
                                                   dialog.dismiss();
                                               }
                                           });
                                       }
                                   })
                                   .setOnBottomDialogDismissListener(new DialogInterface.OnDismissListener() {
                                       @Override
                                       public void onDismiss(DialogInterface dialog) {

                                       }
                                   })
                                   .build()
                                   .show();
                       }else{
                           if (loadingDialog != null) {
                               loadingDialog.show();
                           }
                           viewModel.mRepository.DownLoadVoice("", ItrackConstant.Picture, "", 0, 0, data.getVoice(), new BaseRepository.MyBaseDataCallBack() {
                               @Override
                               public void onDataSuccessCallBack(Object o) {
                                   if (loadingDialog != null) {
                                       loadingDialog.dismiss();
                                   }
                                   List<itemVioceEntity> itemVioceEntities = (List<itemVioceEntity>) o;
                                   List<String> voicePaths = new ArrayList<>();
                                   mItemsVioce = new ArrayList<>();
                                   for (int i = 0; i < itemVioceEntities.size(); i++) {
                                       voicePaths.add(itemVioceEntities.get(i).getViocePath());
                                       mItemsVioce.add(new BottomSheet.BottomListSheetBuilder.BottomSheetListItemData("录音" + i, ""));

                                   }
                                   MediaInfoResponse mediaInfoResponse =new MediaInfoResponse();
                                   mediaInfoResponse.setVoicePtahs(voicePaths);
                                   Vicoedatas.add(mediaInfoResponse);


                                   BottomSheet.BottomListSheetBuilder bottomListSheetBuilder = new BottomSheet.BottomListSheetBuilder(getContext());
                                   bottomListSheetBuilder.setmItems(mItemsVioce);
                                   bottomListSheetBuilder.setIsCenter(true)
                                           .setOnSheetItemClickListener(new BottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                                               @Override
                                               public void onClick(BottomSheet dialog, View itemView, int position, String tag) {
                                                   VioceDialog vioceDialog = VioceDialog.getInstance();
                                                   vioceDialog.show(FragManager, "");

                                                   MediaManager.playSound(Vicoedatas.get(0).getVoicePtahs().get(position), new MediaPlayer.OnCompletionListener() {
                                                       @Override
                                                       public void onCompletion(MediaPlayer mediaPlayer) {
                                                           vioceDialog.dismiss();
                                                           dialog.dismiss();
                                                       }
                                                   });
                                               }
                                           })
                                           .setOnBottomDialogDismissListener(new DialogInterface.OnDismissListener() {
                                               @Override
                                               public void onDismiss(DialogInterface dialog) {
                                                   notifyItemChanged(helper.getAdapterPosition());
                                               }
                                           })
                                           .build()
                                           .show();
                               }

                               @Override
                               public void onDataFailCallBack(Object o, Object t1) {
                                   if (loadingDialog != null) {
                                       loadingDialog.dismiss();
                                   }
                                   XToast.error(getContext(), "下载失败").show();

                               }
                           });
                       }



                } else {
                    XToast.error(getContext(), "暂无数据").show();
                }
            });
            iv_Video.setOnClickListener(v -> {
                XToast.error(getContext(), "暂无数据").show();
            });
//
//        List<BottomSheet.BottomListSheetBuilder.BottomSheetListItemData> mItemsVideo=new ArrayList<>();
//
//        for (int i = 0; i < data.getVideoData().size(); i++) {
//
//
//            mItemsVideo.add(new BottomSheet.BottomListSheetBuilder.BottomSheetListItemData("视频"+i,""));
//        }
//        iv_Video.setOnClickListener(v->{
//
//            if (data.getVideoData()!=null&&data.getVideoData().size()>0) {
//
//                BottomSheet.BottomListSheetBuilder bottomListSheetBuilder = new BottomSheet.BottomListSheetBuilder(getContext());
//                bottomListSheetBuilder.setmItems(mItemsVideo);
//                bottomListSheetBuilder.setIsCenter(true)
//                        .setOnSheetItemClickListener(new BottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
//                            @Override
//                            public void onClick(BottomSheet dialog, View itemView, int position, String tag) {
//                                PictureSelector.create(ActivityTool.getInstance().getLastActivity()).externalPictureVideo(data.getVideoData().get(position).getVideoPath());
//
//
//                            }
//                        })
//                        .build()
//                        .show();
//
//
//            }else{
//                XToast.error(getContext(),"暂无数据").show();
//            }
//        });

        }
    }

